package com.sharecode.stock.init;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.sharecode.stock.service.StockCodeService;
import com.sharecode.stock.service.StockHistoryService;
import com.sharecode.stock.strategy.CalculateHandle;
import com.sharecode.stock.strategy.vo.StrategyVo;
import com.sharecode.stock.vo.stock.StockCode;
import com.sharecode.stock.vo.stock.StockHistory;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class StockInit implements ApplicationRunner {
	public static final Map<String, StrategyVo> STRATEGY_VO_MAP = new ConcurrentHashMap<>();

	@Value(value = "${spring.profiles.active}")
	private String activeFile;
	@Value("${notice.email.send:false}")
	private boolean isSendNotice;
	public static boolean sendNotice = false;
	public static String active = "";
	@Autowired
	private StockCodeService stockCodeService;
	@Autowired
	private StockHistoryService stockHistoryService;

	// 初始化是否通知
	@Override
	public void run(ApplicationArguments args) throws Exception {
		long startTime = System.currentTimeMillis();
		sendNotice = isSendNotice;
		active = activeFile;

		List<StockCode> stockCodes = stockCodeService.getAll();
		log.info("init-code-size->{}", stockCodes.size());
		long start = System.currentTimeMillis();
		int cycle = 1;
		if ("dev".equals(active)) {
//			return;
			CalculateHandle.init_all = true; // 调试开启
		}else {
			//服务器内存不够
			return;
		}
		if ("dev".equals(active)) {
			return;
		}
	 
		
		stockCodes.parallelStream().forEach(stockCode -> {
			StrategyVo vo = new StrategyVo();
			vo.setCode(stockCode.getCode());
			vo.setCycle(cycle);
			STRATEGY_VO_MAP.put(stockCode.getCode() + "-" + cycle, vo);
			List<StockHistory> stockHistories = stockHistoryService.findByCodeAndCycle(stockCode.getCode(), cycle);
			if (CollectionUtils.isNotEmpty(stockHistories)) {
				if ("dev".equals(active)) {
					vo.setInit(true);// 调试开启
				}
				for (StockHistory stockHistory : stockHistories) {
					CalculateHandle.handle(stockHistory);
				}
			}
			vo.setInit(true);
		});
		long totalTime = System.currentTimeMillis() - start;
		log.info("STRATEGY_VO_MAP-size->{},totalTime->{}", STRATEGY_VO_MAP.size(), totalTime);
		CalculateHandle.init_all = true;
		log.info("初始化数据完成,耗时：{}", System.currentTimeMillis() - startTime);
	}
}
